package com.example.jdbc.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShrioConfig {
    Logger log = LoggerFactory.getLogger(ShrioConfig.class);

    @Bean
    public ShiroFilterFactoryBean shrioFilter(SecurityManager securityManager) {
        log.info("加载shrio config");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器
        Map<String, String> filterChainDefaultionMap = new LinkedHashMap<String, String>();
        //配置不会被拦截器的连接，顺序判断
        filterChainDefaultionMap.put("/static/**", "anon");
        filterChainDefaultionMap.put("/doLogin", "anon");
        //配置退出过滤器，其中的具体的退出代码shrio已经替我们实现
        filterChainDefaultionMap.put("/logout", "logout");
        filterChainDefaultionMap.put("/add", "perms[add]");
        // <!-- 过滤链定义，从上向下顺序执行，一般将/**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了;
        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");

        // 未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefaultionMap);
        log.info(" shiro config 加载完毕");
        return shiroFilterFactoryBean;
    }

    @Bean
    public MyShrioRealm myShrioRealm() {
        MyShrioRealm myShrioRealm = new MyShrioRealm();
        return myShrioRealm;
    }

    // 这地方注意下 SecurityManager 在java.lang包下 所以要手动引入 import
    // org.apache.shiro.mgt.SecurityManager; 否则报错
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShrioRealm());
        return securityManager;
    }
    /**
     *  开启shiro aop注解支持.
     *  使用代理方式;所以需要开启代码支持;
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
